﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SiteParser.Core.Logging;
using System.Text.RegularExpressions;
using System.IO;
using SiteParser.Core.Utilites;

namespace SiteParser.Core.ParserEntities
{
	public class ResourceParser : ParserEntity
	{
		public string ResourcesDirectory { get; set; }
		protected const string defaultImagesDirectory = @"d:\resources\images";
		protected const string imageNameRegexPattern = @"[\\/]?([^\\/]+)$";

		protected override void ProcessCurrentContext(ParsingContext context, IHtmlIterator htmlIterator) {
			Logger.Info("Processing current context for 'ImageParser'");

			if (htmlIterator.MoveNext()) {
				string imageName = Regex.IsMatch(htmlIterator.SelectedValue, imageNameRegexPattern) ?
					Regex.Match(htmlIterator.SelectedValue, imageNameRegexPattern).Groups[1].Value : htmlIterator.SelectedValue;

				string imagePath = Path.Combine(ResourcesDirectory ?? defaultImagesDirectory, imageName);
				if (!string.IsNullOrEmpty(PropertyName)) {
					SetPropertyValue(context.InnerEntity, PropertyName, imagePath, true);
				}
				else {
					context.InnerEntity = imagePath;
				}

				try {
					if (!Directory.Exists(defaultImagesDirectory)) {
						Directory.CreateDirectory(defaultImagesDirectory);
					}

					using (FileStream fStream = new FileStream(imagePath, FileMode.OpenOrCreate)) {
						Logger.Info(string.Format("Loading image '{0}'", htmlIterator.SelectedValue));

						using (Stream imageStream = HttpUrlResolver.ResolveReference(htmlIterator.SelectedValue)) {
							Logger.Info(string.Format("Image is loaded. Trying to save it as '{0}'", imagePath));
							int bufferSize = 1000;

							byte[] buffer = new byte[bufferSize];
							int byteRead = 0;

							while ((byteRead = imageStream.Read(buffer, 0, bufferSize)) > 0) {
								fStream.Write(buffer, 0, byteRead);
							}

							Logger.Info("Saved successfully");
						}
					}
				}
				catch (Exception exc) {
					Logger.Info(string.Format("Unable to load the image. {0}", exc));
				}
			}
			else {
				Logger.Info("No items found satisfied the specified expression.");
			}

		}
	}
}
